<?php
class Task extends MY_Controller
{	
	function __construct() {
		parent::__construct();
	}

	function index(){
		$data = $this->user_post_data;
		$this->load->model("Tasks");
		if(empty($data['user_token']['child_id'])){
			echo json_encode(array("code" => 0, "msg" => "缺少孩子ID"));exit;
		}
		$pid = !empty($data['pid']) ? $data['pid'] : 0;
		$week = date('N', time());
		$task_list = $this->Tasks->get_task_list(0,0,array("pid" => $pid, "child_id"=>$data['user_token']['child_id'], "find_ini_set" => $week));
		$task_list_data = array('count' => 0, 'list' => array());
		if(!empty($task_list['count'])){
			$task_list_data['count'] = $task_list['count'];
			foreach ($task_list['list'] as $key => $value) {
				$task_list_data['list'][$value['pid']][] = $value;
			}
		}
		echo json_encode(array("code" => 200, "data" => $task_list_data));
	}

	function get_habit_by_pid(){
		$data = $this->user_post_data;
		$this->load->model("Tasks");
		if(empty($data['user_token']['child_id'])){
			echo json_encode(array("code" => 0, "msg" => "缺少孩子ID"));exit;
		}
		$pid = !empty($data['pid']) ? $data['pid'] : 0;
		$week = date('N', time());
		$task_list = $this->Tasks->get_task_list(0,0,array("pid" => $pid, "child_id"=>$data['user_token']['child_id'], "find_ini_set" => ''));
		

		// $data_obj = array(
  //               'count' => count($task_list),
  //               'list' => $task_list,
  //            );

		// if(!empty($task_list['count'])){
		// 	$task_list_data['count'] = $task_list['count'];
		// 	foreach ($task_list['list'] as $key => $value) {
		// 		$task_list_data['list'][$value['pid']][] = $value;
		// 	}
		// }
		echo json_encode(array("code" => 1, "data" => $task_list));
	}

	function manage_list(){
		$today_week = date('N', time());
		$data = $this->user_post_data;
		$this->load->model("Tasks");
		$task_list = $this->Tasks->get_task_list(0,10,array("child_id"=>$data['user_token']['child_id']));
		if(!empty($task_list['count'])){
			foreach ($task_list['list'] as $key => $value) {
				$task_list['list'][$key]['week'] = '每天';
				$task_list['list'][$key]['is_today'] = 1;
				$weeks = array("1" => "一", "2" => "二", "3" => "三", "4" => "四", "5" => "五", "6" => "六", "7" => "日");
				if($value['repeat']){
					$repeat = explode(",", $value['repeat']);
					if(!in_array($today_week, $repeat)){
						$task_list['list'][$key]['is_today'] = 0;
					}
					$this_weeks = array();
					foreach ($repeat as $k => $v) {
						$this_weeks[] = $weeks[$v];
						unset($weeks[$v]);
					}
					if(count($weeks) <= 0){
						$this_weeks = '每天';
					}elseif (count($weeks) == 5 && !isset($weeks[6]) && !isset($weeks[7])) {
						$this_weeks = '周末';
					}elseif(count($weeks) == 2 && isset($weeks[6]) && isset($weeks[7])){
						$this_weeks = '学习日';
					}else{
						$this_weeks = '周'.implode("、", $this_weeks);
					}
					$task_list['list'][$key]['week'] = $this_weeks;
				}
				
			}
		}
		echo json_encode(array("code" => 200, "data" => $task_list));
	}

	function add(){
		$data = $this->user_post_data;
		$task_data['user_id'] = $data['user_token']['user_id'];
		$task_data['child_id'] = !empty($data['user_token']['child_id']) ? $data['user_token']['child_id'] : 0;
		$task_data['name'] = $data['task_name'];
		$task_data['task_type_id'] = $data['task_type_id'];
		// $task_data['stars'] = !empty($data['stars']) ? $data['stars'] : 0;
		$task_data['repeat'] = !empty($data['repeat']) ? $data['repeat'] : '1,2,3,4,5,6,7';
		$task_data['describe'] = !empty($data['describe']) ? $data['describe'] : NULL;
		if(!empty($data['task_time']) && $data['pid'] == 1){
			$task_data['task_time'] = $data['task_time'];
			$task_time = explode(":", $data['task_time']);
			$task_data['remind_hour'] = $task_time[0];
			$task_data['remind_min'] = $task_time[1];
		}
		if($data['pid'] == 3){
			$task_data['time_long'] = !empty($data['time_long']) ? $data['time_long'] : 0;
		}
		$this->db->insert("tasks", $task_data);
		$task_type_info = get_field_by_where("task_types", "image", "id='{$data['task_type_id']}'");
		echo json_encode(array("code" => 1, "data" => array("id" => $this->db->insert_id(), "image" => $task_type_info['image'])));
	}

	function detail(){
		$data = $this->user_post_data;
		$task_info = get_field_by_where("tasks", "*", "id='{$data['task_id']}'");
		echo json_encode(array("code" => 200, "data" => $task_info));
	}

	function complete(){
		$data = $this->user_post_data;
		$task_info = get_field_by_where("tasks", "*", "id='{$data['task_id']}'");
		if($task_info){
			if($task_info['is_complete'] == 1){
				echo json_encode(array("code" => 0, "msg" => "该任务已完成，不需要重复操作哦:)"));
			}else{
				$this->db->update("tasks", array("is_complete" => 1), array("id" => $task_info['id']));
				$task_record['user_id'] = $task_info['user_id'];
				$task_record['child_id'] = $task_info['child_id'];
				$task_record['task_id'] = $task_info['id'];
				$task_record['task_name'] = $task_info['name'];
				$task_record['stars'] = 0;
				$task_record['time'] = time();
				$this->db->insert("task_records", $task_record);
				echo json_encode(array("code" => 200));
			}
		}else{
			echo json_encode(array("code" => 0, "msg" => "任务不存在"));
		}
	}

	function delete(){
		$data = $this->user_post_data;
		$task_info = get_field_by_where("tasks", "*", "id='{$data['task_id']}'");
		if($task_info['user_id'] != $data['user_token']['user_id']){
			echo json_encode(array("code" => 0, "msg" => "无法删除该任务"));
			exit;
		}
		$this->db->where("id", $data['task_id']);
		$this->db->delete("tasks");
		if($this->db->affected_rows() > 0){
			echo json_encode(array("code" => 1, "msg" => "删除成功"));	
		}else{
			echo json_encode(array("code" => 0, "msg" => "删除失败，请重试"));
		}
	}

	function task_add_start(){
        $data = $this->user_post_data;
   		//获取任务数据，限制最多可以加多少星，防止被刷
        $task_info = get_field_by_where("tasks", "id,user_id,name,task_type_id", "id='{$data['task_id']}'");
        if($task_info['user_id'] != $data['user_token']['user_id']){
			echo json_encode(array("code" => 0, "msg" => "无法操作该任务"));
			exit;
		}
		$time = time();
        //获取任务记录数据，如果没有记录就要添加新记录
        $today = strtotime(date("Y-m-d", $time));
        $where = "child_id='{$data['user_token']['child_id']}' AND time >= $today AND task_id = '{$data['task_id']}'";
        $task_record_info = get_field_by_where("task_records", "*", $where);
        $action = '';
        if($task_record_info){
            $stars = !empty($data['stars']) ? 1 : 0;
            $this->db->update("task_records", array("stars" => $stars), array("id" => $task_record_info['id']));
            if($this->db->affected_rows() > 0){
            	if($stars == 1){
            		$action = 'plus';
            		$this->db->where("id", $data['user_token']['child_id']);
		            $this->db->set("stars", "stars + 1", false);
		            $this->db->update("user_childrens");
            	}else{
            		$action = 'minus';
            		$this->db->where("id", $data['user_token']['child_id']);
		            $this->db->set("stars", "stars - 1", false);
		            $this->db->update("user_childrens");
            	}
            }
        }else{
        	$action = 'plus';
            $task_recode_data['user_id']    = $data['user_token']['user_id'];
            $task_recode_data['child_id']   = $data['user_token']['child_id'];
            $task_recode_data['task_id']    = $data['task_id'];
            $task_recode_data['task_name']  = $task_info['name'];
            $task_recode_data['stars']      = 1;
            $task_recode_data['time']       = time();
            $this->db->insert("task_records", $task_recode_data);
            $this->db->where("id", $data['user_token']['child_id']);
            $this->db->set("stars", "stars + 1", false);
            $this->db->update("user_childrens");
        }

        $today_stars_info = get_field_by_where("user_children_today_stars", "*", "child_id='{$data['user_token']['child_id']}'");
        if(!$today_stars_info){
            $today_stars['user_id'] = $data['user_token']['user_id'];
            $today_stars['child_id'] = $data['user_token']['child_id'];
            $today_stars['stars'] = ($action == 'plus') ? 1 : 0;
            $today_stars['last_time'] = $time;
            $this->db->insert("user_children_today_stars", $today_stars);
        }else{
        	$stars = ($action == 'plus') ? 1 : -1;
            $today_time = strtotime(date('Y-m-d',$time));
            if($today_stars_info['last_time'] >= $today_time){
                $this->db->set("stars", "stars + " . $stars, false);
                $this->db->set("last_time", $time);
                $this->db->where("id", $today_stars_info['id']);
                $this->db->update("user_children_today_stars");
            }else{
                $this->db->update("user_children_today_stars", array("stars" => $stars, "last_time" => $time), array("id" => $today_stars_info['id']));
            }
        }

        $today_time = strtotime(date("Y-m-d", $time));	//今天的开始时间
        $yesterday_time = $today_time - 3600 * 24;		//昨天的开始时间
        $this->load->model("Users");
        $task_statistics_info = $this->Users->get_user_children_task_type_statistics($data['user_token']['child_id'], $data['task_id']);

        if($task_statistics_info){
        	//如果任务统计的最后连续时间大于昨天的开始时间而且小于今天的开始时间就表示是连续了任务
        	if($action == 'plus'){
        		if($task_statistics_info['last_time'] >= $yesterday_time && $task_statistics_info['last_time'] < $today_time){
        			$this->db->set("total_stars", "total_stars + 1", false);
        			$this->db->set("continuity", "continuity + 1", false);
        			$this->db->set("last_time", $time);
        			$this->db->set("befor_time", $task_statistics_info['last_time']);
        			$this->db->where("id", $task_statistics_info['id']);
        			$this->db->update("user_children_task_type_statistics");
        			
        			$user_children_max_continuity_record = get_field_by_where("user_children_max_continuity_record", "id,end_time", "child_id = '{$data['user_token']['child_id']}' AND task_id='{$data['task_id']}' ORDER BY id DESC");
        			if($user_children_max_continuity_record['end_time'] < $today_time){
        				$sql = "UPDATE {$this->db->dbprefix}user_children_max_continuity_record SET continuity = continuity + 1, end_time = '{$time}' WHERE child_id = '{$data['user_token']['child_id']}' AND task_id='{$data['task_id']}' ORDER BY id DESC LIMIT 1";
        				$this->db->query($sql);
        			}
        		}else{
        			$this->db->set("continuity", "1");
        			$this->db->set("last_time", $time);
        			$this->db->set("befor_time", $task_statistics_info['last_time']);
        			$this->db->set("total_stars", "total_stars + 1", false);
        			$this->db->where("id", $task_statistics_info['id']);
        			$this->db->update("user_children_task_type_statistics");

        			//写入用户任务类型最长连续天数统计历史表
	    			$continuity_record_data['user_id'] = $data['user_token']['user_id'];
	    			$continuity_record_data['child_id'] = $data['user_token']['child_id'];
	    			$continuity_record_data['task_id'] = $data['task_id'];
	    			$continuity_record_data['task_type_id'] = $task_info['task_type_id'];
	    			$continuity_record_data['continuity'] = 1;
	    			$continuity_record_data['start_time'] = $time;
	    			$continuity_record_data['end_time'] = $time;
	    			$this->db->insert("user_children_max_continuity_record", $continuity_record_data);
        		}
        	}else{
        		if($task_statistics_info['last_time'] >= $yesterday_time && $task_statistics_info['last_time'] < $today_time){
        			$this->db->set("continuity", "continuity - 1", false);
        			$this->db->set("total_stars", "total_stars - 1", false);
        			// $this->db->set("befor_time", $task_statistics_info['last_time']);
        			$this->db->set("last_time", $task_statistics_info['befor_time']);
        			$this->db->where("id", $task_statistics_info['id']);
        			$this->db->update("user_children_task_type_statistics");

        			$sql = "UPDATE {$this->db->dbprefix}user_children_max_continuity_record SET continuity = continuity - 1, end_time = '{$yesterday_time}' WHERE child_id = '{$data['user_token']['child_id']}' AND task_id='{$data['task_id']}' ORDER BY id DESC LIMIT 1";
        			$this->db->query($sql);
        		}elseif($task_statistics_info['last_time'] >= $yesterday_time && $task_statistics_info['last_time'] > $today_time){
        			$this->db->set("continuity", "continuity - 1", false);
        			$this->db->set("total_stars", "total_stars - 1", false);
        			$this->db->set("last_time", $task_statistics_info['befor_time']);
        			$this->db->where("id", $task_statistics_info['id']);
        			$this->db->update("user_children_task_type_statistics");

        			$sql = "UPDATE {$this->db->dbprefix}user_children_max_continuity_record SET continuity = continuity - 1, end_time = '{$yesterday_time}' WHERE child_id = '{$data['user_token']['child_id']}' AND task_id='{$data['task_id']}' ORDER BY id DESC LIMIT 1";
    				$this->db->query($sql);
    				
        			$sql = "DELETE FROM {$this->db->dbprefix}user_children_max_continuity_record WHERE child_id = '{$data['user_token']['child_id']}' AND task_id='{$data['task_id']}' AND start_time >= $today_time";
        			$this->db->query($sql);
        		}else{
        			$this->db->set("continuity", "1");
        			$this->db->set("last_time", $time);
        			$this->db->set("last_time", $task_statistics_info['befor_time']);
        			$this->db->set("total_stars", "total_stars - 1", false);
        			$this->db->where("id", $task_statistics_info['id']);
        			$this->db->update("user_children_task_type_statistics");
        		}
        	}
        }else{
        	if($action == 'plus'){
        		$task_statistics_data['user_id'] = $data['user_token']['user_id'];
        		$task_statistics_data['child_id'] = $data['user_token']['child_id'];
        		$task_statistics_data['task_id'] = $data['task_id'];
        		$task_statistics_data['task_type_id'] = $task_info['task_type_id'];
        		$task_statistics_data['total_stars'] = 1;
        		$task_statistics_data['continuity'] = 1;
        		$task_statistics_data['first_time'] = $time;
        		$task_statistics_data['last_time'] = $time;
        		$task_statistics_data['befor_time'] = $time;
        		$this->db->insert("user_children_task_type_statistics", $task_statistics_data);

        		//写入用户任务类型最长连续天数统计历史表
    			$continuity_record_data['user_id'] = $data['user_token']['user_id'];
    			$continuity_record_data['child_id'] = $data['user_token']['child_id'];
    			$continuity_record_data['task_id'] = $data['task_id'];
    			$continuity_record_data['task_type_id'] = $task_info['task_type_id'];
    			$continuity_record_data['continuity'] = 1;
    			$continuity_record_data['start_time'] = $time;
    			$continuity_record_data['end_time'] = $time;
    			$this->db->insert("user_children_max_continuity_record", $continuity_record_data);
        	}
        }
        echo json_encode(array("code" => 1, "msg" => "加星成功", "action" => $action));   //  
    }
}